package com.chen.webuser.service.impl;

import com.chen.util.RedisKey;
import com.chen.webuser.entity.WebUser;
import com.chen.webuser.entity.WebUserLog;
import com.chen.webuser.mapper.WebUserLogMapper;
import com.chen.webuser.service.WebUserLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chen
 * @since 2025-10-19
 */
@Service
public class WebUserLogServiceImpl extends ServiceImpl<WebUserLogMapper, WebUserLog> implements WebUserLogService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 保存日志
     *
     * @param sqlUser
     */
    @Override
    public void saveLog(WebUser sqlUser) {


        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern("YYYYMMDD"));
        String key = String.format(RedisKey.userLoginFirstTime, sqlUser.getUid(), date);


        //看看今天有没有存储第一次登录的时间
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {

            //封装WebUserLog对象
            WebUserLog webUserLog = new WebUserLog();
            webUserLog.setUid(sqlUser.getUid());
            //只存储第一次登录时间
            webUserLog.setLoginTime(LocalDateTime.now());

            //存储日志
            save(webUserLog);

            //存储
            redisTemplate.opsForValue().set(key, webUserLog, 1, TimeUnit.DAYS); //一天过期


        }//啥也不做

    }
}
